<?php

namespace App\Http\Controllers;

use App\Http\Requests\UserLoginRequest;
use App\Http\Requests\UserRegisterRequest;
use App\Models\User;
use App\Services\UserService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use Jiannei\Response\Laravel\Support\Facades\Response;

class UserController extends Controller
{
    /**
     * Register user.
     * @param UserRegisterRequest $request
     * @return JsonResponse
     */
    public function register(UserRegisterRequest $request): JsonResponse
    {
        try {
            $params = $request->only(['phone', 'password', 'avatar', 'expire']);
            $params = array_filter($params);
            $user = UserService::storeUser($params);
            /** @var User $user */
            $data['token'] = $user->createToken(config('common.salt'))->plainTextToken;
            return Response::success($data);
        } catch (\Exception $e) {
            return Response::fail($e->getMessage());
        }
    }

    /**
     * Login user.
     * @param UserLoginRequest $request
     * @return JsonResponse
     */
    public function login(UserLoginRequest $request): JsonResponse
    {
        try {
            $params = $request->only(['phone', 'password']);
            $user = UserService::getUserByPhone($params['phone']);

            if (!$user) {
                throw new \Exception("user not exists");
            }

            if (!Hash::check($params['password'], $user->password)) {
                throw new \Exception('The account or password is incorrect');
            }

            $data['token'] = $user->createToken(config('common.salt'))->plainTextToken;
            return Response::success($data);
        } catch (\Exception $e) {
            return Response::fail($e->getMessage());
        }
    }

    /**
     * Get user info.
     * @param Request $request
     * @return JsonResponse
     */
    public function info(Request $request): JsonResponse
    {
        try {
            $user = $request->user();
            return Response::success($user);
        } catch (\Exception $e) {
            return Response::fail($e->getMessage());
        }
    }
}
